// 主题管理工具 - 重新创建
export type UITheme = 'ios' | 'material' | 'auto'

export class ThemeManager {
  private static instance: ThemeManager
  private currentTheme: UITheme = 'auto'
  private listeners: ((theme: 'ios' | 'material') => void)[] = []

  static getInstance(): ThemeManager {
    if (!ThemeManager.instance) {
      ThemeManager.instance = new ThemeManager()
    }
    return ThemeManager.instance
  }

  // 自动检测平台
  detectPlatform(): 'ios' | 'material' {
    if (typeof window === 'undefined') return 'material'

    const userAgent = navigator.userAgent.toLowerCase()

    if (/iphone|ipad|ipod/.test(userAgent)) {
      return 'ios'
    }

    return 'material'
  }

  // 获取当前应该使用的主题
  getCurrentTheme(): 'ios' | 'material' {
    if (this.currentTheme === 'auto') {
      return this.detectPlatform()
    }
    return this.currentTheme
  }

  // 设置主题
  setTheme(theme: UITheme) {
    this.currentTheme = theme
    if (typeof window !== 'undefined') {
      localStorage.setItem('ui-theme', theme)
    }
    this.notifyListeners()
  }

  // 添加主题变化监听器
  addListener(callback: (theme: 'ios' | 'material') => void) {
    this.listeners.push(callback)
    return () => {
      this.listeners = this.listeners.filter((l) => l !== callback)
    }
  }

  // 通知监听器
  private notifyListeners() {
    const currentTheme = this.getCurrentTheme()
    this.listeners.forEach((listener) => listener(currentTheme))
  }

  // 初始化
  init() {
    if (typeof window !== 'undefined') {
      const savedTheme = localStorage.getItem('ui-theme') as UITheme
      if (savedTheme) {
        this.currentTheme = savedTheme
      }
    }
    this.notifyListeners()
  }
}

// React Hook
export const useTheme = () => {
  const [theme, setThemeState] = useState<'ios' | 'material'>('material')
  const themeManager = ThemeManager.getInstance()

  useEffect(() => {
    themeManager.init()
    setThemeState(themeManager.getCurrentTheme())

    const unsubscribe = themeManager.addListener(setThemeState)
    return unsubscribe
  }, [])

  const setTheme = (newTheme: UITheme) => {
    themeManager.setTheme(newTheme)
  }

  return { theme, setTheme }
}

// 需要添加 React 导入
import { useState, useEffect } from 'react'
